package com.fan.shop.services;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;

import com.fan.shop.dao.RoleDao;
import com.fan.shop.dao.UserDao;
import com.fan.shop.domain.User;
import com.fan.shop.global.ShopGlobalVariables;

/**
 * 
 * User Service
 * 
 * @author onlinetechvision.com
 * @since 25 Mar 2012
 * @version 1.0.0
 * 
 */
@Named("userService")
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {

	// UserDAO is injected...
	@Inject
	@Named("userDao")
	private UserDao userDao;

	@Inject
	@Named("roleDao")
	private RoleDao roleDao;

	private User currentUser;

	/**
	 * Add User
	 * 
	 * @param User
	 *            user
	 */
	@Transactional(readOnly = false)
	public void addUser(User user) {
		getUserDao().addUser(user);
	}

	/**
	 * Delete User
	 * 
	 * @param User
	 *            user
	 */
	@Transactional(readOnly = false)
	public void deleteUser(User user) {
		getUserDao().deleteUser(user);
	}

	/**
	 * Update User
	 * 
	 * @param User
	 *            user
	 */
	@Transactional(readOnly = false)
	public void updateUser(User user) {
		getUserDao().updateUser(user);
	}

	/**
	 * Get User
	 * 
	 * @param int User Id
	 */
	public User getUser(String id) {
		return getUserDao().getUser(id);
	}

	/**
	 * Get User List
	 * 
	 */
	public List<User> getAllUsers() {
		return getUserDao().getAllUsers();
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public RoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	public boolean hasUser(String username) {
		return userDao.hasUser(username);
	}

	public User getCurrentUser() {
		org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder
				.getContext().getAuthentication().getPrincipal();

		currentUser = getUser(user.getUsername());
		return currentUser;
	}

	public void setCurrentUser(User user) {
		this.currentUser = user;

	}

	@SuppressWarnings("rawtypes")
	public List getList() {
		return getAllUsers();
	}

	public List<String> getColumnNames() {
		return userDao.getColumnNames();
	}

	public int getColumnsSize() {
		return getColumnNames().size();
	}

	public Object copy(Object obj) {
		// TODO Auto-generated method stub
		return null;
	}

	public String getCurrentUserGroup() {
		return roleDao.getUserGroup(getCurrentUser().getUsername());
	}

	public boolean isCurrentUserGroupAdmin() {
		if (getCurrentUserGroup().equals(ShopGlobalVariables.ADMIN)) {
			return true;
		} else {
			return false;
		}
	}

}
